package com.link2room.aeriabots.facade.impl;

import com.link2room.aeriabots.dto.result.base.WxReplyTemplateDetailDto;
import com.link2room.aeriabots.dto.result.base.WxReplyTemplateDto;
import com.link2room.aeriabots.facade.IWXReplyFacadeService;
import com.link2room.aeriabots.service.IWxKeyWordReplyService;
import com.link2room.common.enums.BaseSysExceptionEnum;
import com.link2room.common.exception.SysException;
import com.link2room.common.jpa.result.QueryResult;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.ClassConverUtil;
import com.link2room.common.util.L2RAssert;
import com.link2room.common.util.StringUtil;
import com.link2room.aeriabots.dto.param.api.WxReplyKeyApiParamDto;
import com.link2room.aeriabots.dto.param.api.WxReplyTemplateApiParamDto;
import com.link2room.aeriabots.dto.result.api.WxReplyKeyMappingDto;
import com.link2room.aeriabots.entity.WxReplyKeyMapping;
import com.link2room.aeriabots.entity.WxReplyTemplate;
import com.link2room.aeriabots.entity.WxReplyTemplateDetail;
import com.link2room.aeriabots.mapper.WxReplyKeyMapper;
import com.link2room.enums.exception.AeriabotsSysExceptionEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by LN on 2016/12/1.
 */
@Component("wxReplyFacadeService")
public class WXReplyFacadeServiceImpl implements IWXReplyFacadeService {
    @Resource
    private ICommonService commonServiceSupport;
    @Resource
    private IWxKeyWordReplyService wxKeyWordReplyService;

    @Override
    public QueryResult<WxReplyTemplateDto> getWxReplyTemplates(WxReplyTemplateApiParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        L2RAssert.stringBlank(paramDto.getLhotelGroupCode(),"[lhotelGroupCode] is blank.");
        Integer currentPage = paramDto.getCurrentPage();
        Integer pageSize = paramDto.getPageSize();
        if(currentPage == null){
            currentPage = 1;
        }
        if(pageSize == null || pageSize > 100){
            pageSize = 5;
        }
        WxReplyTemplate find = new WxReplyTemplate();
        find.setLhotelGroupCode(lhotelGroupCode);
        find.setIsHalt("F");
        QueryResult<WxReplyTemplate> queryRes = commonServiceSupport.findAllEQ(WxReplyTemplate.class, find, currentPage, pageSize);
        if(queryRes != null && queryRes.getTotalrecord() > 0){
            List<WxReplyTemplateDto> list = queryRes.getResultlist().stream()
                    .map(templateEntity -> ClassConverUtil.copyProperties(templateEntity, WxReplyTemplateDto.class))
                    .collect(Collectors.toList());
            QueryResult res = new QueryResult();
            res.setResultlist(list);
            res.setTotalrecord(queryRes.getTotalrecord());
            res.setCurrentPage(queryRes.getCurrentPage());
            return res;
        }else{
            QueryResult res = new QueryResult();
            res.setTotalrecord(0);
            return res;
        }
    }

    @Override
    public QueryResult<WxReplyTemplateDto> getWxReplyTemplateDetails(WxReplyTemplateApiParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        L2RAssert.stringBlank(paramDto.getLhotelGroupCode(),"[lhotelGroupCode] is blank.");
        String templateName = paramDto.getTemplateName();
        Integer currentPage = paramDto.getCurrentPage();
        Integer pageSize = paramDto.getPageSize();
        if(currentPage == null){
            currentPage = 1;
        }
        if(pageSize == null || pageSize > 100){
            pageSize = 5;
        }
        WxReplyTemplate find = new WxReplyTemplate();
        find.setLhotelGroupCode(lhotelGroupCode);
        find.setTemplateName(templateName);
        find.setTemplateId(paramDto.getTemplateId());
        find.setIsHalt(paramDto.getIsHalt());
        QueryResult<WxReplyTemplate> queryRes = commonServiceSupport.findAllEQ(WxReplyTemplate.class, find, currentPage, pageSize);
        if(queryRes != null && queryRes.getTotalrecord() > 0){
            return convertToReplyDto(queryRes);
        }else{
            QueryResult res = new QueryResult();
            res.setTotalrecord(0);
            return res;
        }
    }

    @Override
    public void createWxReplyTemplate(WxReplyTemplateApiParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        L2RAssert.stringBlank(paramDto.getLhotelGroupCode(),"[lhotelGroupCode] is blank.");

        String templateName = paramDto.getTemplateName();
        String msgType = paramDto.getMsgType();
        if(StringUtil.isBlank(templateName) || StringUtil.isBlank(msgType) ){
            return;
        }
        if(!hadTemplate(lhotelGroupCode,templateName)){
            throw new SysException(AeriabotsSysExceptionEnum.WX_REPLY_REPETITION);
        }
        WxReplyTemplateDetailDto articles = paramDto.getTemplateDetail();
        if(articles == null){
            return;
        }
        String templateId = Long.valueOf(System.currentTimeMillis()).toString();
        //关键字创建
        if(WxReplyTemplate._MsgType.news.toString().equals(msgType)){
            WxReplyTemplate wxReplyTemplate = new WxReplyTemplate();
            wxReplyTemplate.setTemplateName(templateName);
            wxReplyTemplate.setMsgType(msgType);
            wxReplyTemplate.setTemplateId(templateId);
            wxReplyTemplate.setLhotelGroupCode(lhotelGroupCode);
            //图文回复
            List<WxReplyTemplateDetailDto._Detail> replyArticles = articles.getWxReplyTemplateDetails();
            if(replyArticles == null ||replyArticles.size() == 0){
                throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(),
                        BaseSysExceptionEnum.INVALID_PARA.getMsg()+"[wxReplyArticles] is null",
                        BaseSysExceptionEnum.INVALID_PARA.getBizType());
            }
            List<WxReplyTemplateDetail> articleEntities = replyArticles.stream()
                    .map(dto -> detailDtoToEntity(dto,lhotelGroupCode,templateId))
                    .collect(Collectors.toList());
            wxKeyWordReplyService.save(wxReplyTemplate,articleEntities);
        }
    }

    @Override
    public void updateReplyTamplate(WxReplyTemplateApiParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        L2RAssert.stringBlank(paramDto.getLhotelGroupCode(),"[lhotelGroupCode] is blank.");

        String templateName = paramDto.getTemplateName();
        String msgType = paramDto.getMsgType();
        String templateId = paramDto.getTemplateId();
        if(StringUtil.isBlank(templateName) || StringUtil.isBlank(msgType) ){
            return;
        }
        WxReplyTemplateDetailDto articles = paramDto.getTemplateDetail();

        List<Long> delIds = paramDto.getDelDetealList();

        List<WxReplyTemplateDetailDto._Detail> articleList = articles.getWxReplyTemplateDetails();
        List<WxReplyTemplateDetail> articleEntityList = null;
        if(articleList != null){
            articleEntityList = articleList.stream()
                    .filter(entity->entity != null)
                    .map(entity -> _templateDetailDtoToEntity(lhotelGroupCode,entity,templateId))
                    .collect(Collectors.toList());
        }
        //wordEntity
        WxReplyTemplate wordEntity = new WxReplyTemplate();
//        findWordEentity.setTemplateId(templateId);
//        findWordEentity.setLhotelGroupCode(lhotelGroupCode);
//        WxReplyTemplate wordEntity = commonServiceSupport.findOneEQ(WxReplyTemplate.class, findWordEentity);
        ClassConverUtil.copyProperties(paramDto,wordEntity);
        wxKeyWordReplyService.update(wordEntity,articleEntityList,delIds);

    }

    @Override
    public void delReplyTemplate(WxReplyTemplateApiParamDto paramDto) throws Exception {
        String templateId = paramDto.getTemplateId();
        WxReplyTemplate find = new WxReplyTemplate();
        find.setLhotelGroupCode(paramDto.getLhotelGroupCode());
        find.setTemplateId(templateId);
        QueryResult<WxReplyTemplate> queryKeyWrodsRes = commonServiceSupport.findAllEQ(WxReplyTemplate.class, find);
        if(queryKeyWrodsRes !=null && queryKeyWrodsRes.getResultlist() != null){
            queryKeyWrodsRes.getResultlist().forEach(keyWordEntity-> delReplyTemplate(keyWordEntity));
        }
    }

    @Override
    public QueryResult getReplyKeys(WxReplyKeyApiParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        L2RAssert.stringBlank(paramDto.getLhotelGroupCode(),"[lhotelGroupCode] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyType(),"[keyType] is blank.");
        Integer currentPage = paramDto.getCurrentPage();
        if(currentPage == null || currentPage <= 0){
            currentPage = 1;
        }
        Integer pageSize = paramDto.getPageSize();
        if(pageSize == null || pageSize < 0){
            pageSize = 10;
        }
        QueryResult<WxReplyKeyMapper> queryRes = wxKeyWordReplyService.findWxReplyKeyMapper(paramDto, currentPage, pageSize);
        if(queryRes == null || queryRes.getTotalrecord() == 0 || queryRes.getResultlist()==null){
            return queryRes;
        }else{
            List<WxReplyKeyMappingDto> res = queryRes.getResultlist().stream()
                    .map(queryMapper -> ClassConverUtil.copyProperties(queryMapper, WxReplyKeyMappingDto.class))
                    .collect(Collectors.toList());
            QueryResult result = new QueryResult();
            result.setCurrentPage(queryRes.getCurrentPage());
            result.setTotalrecord(queryRes.getTotalrecord());
            result.setResultlist(res);
            return result;
        }
    }

    @Override
    public void createKey(WxReplyKeyApiParamDto paramDto) throws Exception {
        L2RAssert.stringBlank(paramDto.getLhotelGroupCode(),"[lhotelGroupCode] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyName(),"[keyName] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyType(),"[keyType] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyValue(),"[keyValue] is blank.");
        WxReplyKeyMapping mappingEntity = new WxReplyKeyMapping();
        ClassConverUtil.copyProperties(paramDto,mappingEntity);
        mappingEntity.setKeyId(this.createKeyId());
        commonServiceSupport.save(mappingEntity);
    }

    @Override
    public void updateKey(WxReplyKeyApiParamDto paramDto) throws Exception {
        L2RAssert.numberNull(paramDto.getId(),"[id] is null.");
        L2RAssert.stringBlank(paramDto.getLhotelGroupCode(),"[lhotelGroupCode] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyName(),"[keyName] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyType(),"[keyType] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyValue(),"[keyValue] is blank.");
        L2RAssert.stringBlank(paramDto.getKeyId(),"[keyValue] is keyId.");
        WxReplyKeyMapping mappingEntity = new WxReplyKeyMapping();
        ClassConverUtil.copyProperties(paramDto,mappingEntity);
        commonServiceSupport.updateById(mappingEntity);
    }

    @Override
    public void deleteKey(WxReplyKeyApiParamDto paramDto) throws Exception {
        String keyId = paramDto.getKeyId();
        L2RAssert.stringBlank(paramDto.getKeyId(),"[keyId] is null.");
        WxReplyKeyMapping find = new WxReplyKeyMapping();
        find.setLhotelGroupCode(paramDto.getLhotelGroupCode());
        find.setKeyId(keyId);
        WxReplyKeyMapping mappEntity = commonServiceSupport.findOneEQ(WxReplyKeyMapping.class, find);
        if(mappEntity!=null){
            commonServiceSupport.delete(WxReplyKeyMapping.class,mappEntity.getId());
        }
    }


    private String createKeyId(){
        return Long.valueOf(System.nanoTime()).toString();
    }
    private void delReplyTemplate(WxReplyTemplate keyWordEntity )  {
        if(keyWordEntity == null){
            return;
        }
        /**
         * 图文
         */
        if(WxReplyTemplate._MsgType.news.toString().equals(keyWordEntity.getMsgType())){
            String templateId = keyWordEntity.getTemplateId();
            WxReplyTemplateDetail find = new WxReplyTemplateDetail();
            find.setTemplateId(templateId);
            QueryResult<WxReplyTemplateDetail> queryArticle = null;
            try {
                queryArticle = commonServiceSupport.findAllEQ(WxReplyTemplateDetail.class, find);
            } catch (Exception e) {
                throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION,e);
            }
            List<WxReplyTemplateDetail> articlList = queryArticle.getResultlist();
            try {
                wxKeyWordReplyService.delReply(keyWordEntity,articlList);
            } catch (Exception e) {
                throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION,e);
            }
        }



    }
    private WxReplyTemplateDetail _templateDetailDtoToEntity(String lhotelGroupCode , WxReplyTemplateDetailDto._Detail dto, String keyCode){
        try {
            if(dto != null){
                WxReplyTemplateDetail entity = ClassConverUtil.copyProperties(dto, WxReplyTemplateDetail.class);
                entity.setLhotelGroupCode(lhotelGroupCode);
                entity.setTemplateId(keyCode);
                return entity;
            }else{
                return null;
            }
        } catch (Exception e) {
            throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION);
        }
    }
    /**
     * 检测是否有 templateName
     * @param lhotelGroupCode
     * @param templateName
     * @return
     * @throws Exception
     */
    private boolean hadTemplate(String lhotelGroupCode, String templateName) throws Exception {
        WxReplyTemplate check = new WxReplyTemplate();
        check.setLhotelGroupCode(lhotelGroupCode);
        check.setTemplateName(templateName);
        check.setIsHalt("F");
        long count = commonServiceSupport.getCountAllEQ(WxReplyTemplate.class, check, null);
        if(count == 0){
            return true;
        }else{
            return false;
        }

    }
    private WxReplyTemplateDetail detailDtoToEntity(WxReplyTemplateDetailDto._Detail dto, String lhotelGroupCode, String templateId){

        try {
            WxReplyTemplateDetail aritcle = new WxReplyTemplateDetail();
            ClassConverUtil.copyProperties(dto,aritcle);
            aritcle.setTemplateId(templateId);
            aritcle.setLhotelGroupCode(lhotelGroupCode);
            return aritcle;
        } catch (Exception e) {
            throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION);
        }
    }
    private QueryResult<WxReplyTemplateDto> convertToReplyDto(QueryResult<WxReplyTemplate> queryEntities) throws Exception {
        List<WxReplyTemplate> resList = queryEntities.getResultlist();
        long totalRecord = queryEntities.getTotalrecord();
        Integer currentPage = queryEntities.getCurrentPage();
        QueryResult<WxReplyTemplateDto> res = new QueryResult();
        res.setTotalrecord(totalRecord);
        res.setCurrentPage(currentPage);
        if(resList != null){
            List<WxReplyTemplateDto> replyDtoList = resList.stream()
                    .map(entity->this.getTamplateDtoByName(entity))
                    .collect(Collectors.toList());
            res.setResultlist(replyDtoList);
        }
        return res;
    }


    private WxReplyTemplateDto getTamplateDtoByName(WxReplyTemplate entity ) {
        WxReplyTemplateDto replyDto = new WxReplyTemplateDto();
        replyDto.setId(entity.getId());
        replyDto.setTemplateName(entity.getTemplateName());
        replyDto.setMsgType(entity.getMsgType());
        replyDto.setTemplateId(entity.getTemplateId());
        //图文回复
        if(WxReplyTemplate._MsgType.news.toString().equals(entity.getMsgType())){
            List<WxReplyTemplateDetail> wxReplyTemplateDetails = null;
            try {
                wxReplyTemplateDetails = findReplyTamplateDetail(entity);
            } catch (Exception e) {
                throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION.getCode(),e);
            }
            WxReplyTemplateDetailDto articlesDto = new WxReplyTemplateDetailDto();
            if(wxReplyTemplateDetails != null && wxReplyTemplateDetails.size() > 0){
                List<WxReplyTemplateDetailDto._Detail> _details = wxReplyTemplateDetails.stream()
                        .map(articleEntity -> detailEntityTo_WxReplyDetail(articleEntity) )
                        .sorted(Comparator.comparing(WxReplyTemplateDetailDto._Detail::getListOrder))
                        .collect(Collectors.toList());
                articlesDto.setWxReplyTemplateDetails(_details);
            }
            replyDto.setMsgReply(articlesDto);
            return replyDto;
        }else if(WxReplyTemplate._MsgType.image.toString().equals(entity.getMsgType())){
            /**其他回复**/
        }
        return null;
    }

    private WxReplyTemplateDetailDto._Detail detailEntityTo_WxReplyDetail(WxReplyTemplateDetail articleEntity ){
        try {
            return ClassConverUtil.copyProperties(articleEntity,WxReplyTemplateDetailDto._Detail.class);
        } catch (Exception e) {
            throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION);
        }
    }

    private List<WxReplyTemplateDetail> findReplyTamplateDetail(WxReplyTemplate entity) throws Exception {
        if(entity == null || StringUtil.isBlank(entity.getTemplateId())){
            return null;
        }
        WxReplyTemplateDetail find = new WxReplyTemplateDetail();
        find.setIsHalt("F");
        find.setTemplateId(entity.getTemplateId());
        find.setLhotelGroupCode(entity.getLhotelGroupCode());
        QueryResult<WxReplyTemplateDetail> query = commonServiceSupport.findAllEQ(WxReplyTemplateDetail.class, find);
        if(query != null){
            return query.getResultlist();
        }else{
            return null;
        }
    }
}
